/**
 * Project Name: mms-provider-user
 * File Name: EmployeeServiceImpl
 * Package Name: com.scb.dev.mms.service.impl
 * Date: 2018/11/27 9:10 PM
 * Copyright (c) 2018, Wang, Haoyue All Rights Reserved.
 */
package com.scb.dev.mms.service.impl;

import com.scb.dev.mms.common.DataCommon;
import com.scb.dev.mms.common.ResponseResult;
import com.scb.dev.mms.common.ResultType;
import com.scb.dev.mms.common.StatusCode;
import com.scb.dev.mms.dao.AccountMapper;
import com.scb.dev.mms.dao.DepartmentMapper;
import com.scb.dev.mms.dao.EmployeeMapper;
import com.scb.dev.mms.dao.PositionMapper;
import com.scb.dev.mms.feign.AuthorityFeign;
import com.scb.dev.mms.pojo.Employee;
import com.scb.dev.mms.service.IEmployeeService;
import com.scb.dev.mms.util.UUIDTool;
import com.scb.dev.mms.vo.EmployeeInfoVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: EmployeeServiceImpl
 * Description: EmployeeService
 * Date: 2018/11/27 9:10 PM
 *
 * @author Wang, Haoyue
 * @version V1.0
 * @since JDK 1.8
 */
@Slf4j
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private AccountMapper accountMapper;

    @Autowired
    private AuthorityFeign authorityFeign;

    /**
     * insertEmployee: add employee
     *
     * @param employee  new employee
     * @return  success: {true, "添加成功", 202}
     */
    @Override
    public ResponseResult insertEmployee(Employee employee, String accountId) {
        if (employee == null) {
            log.info("参数为空,添加职员失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        employee.setEmployeeId(UUIDTool.generateUUID());
        employee.setEmployeeCreatorAccountId(accountId);
        if (employeeMapper.insertSelective(employee) == 0) {
            log.info("添加职员执行失败");
            return new ResponseResult(false, ResultType.ADD_ERROR, StatusCode.ADDERROR);
        }
        log.info("Employee Service -> insertEmployee 添加职员成功");
        return new ResponseResult(true, ResultType.ADD_SUCCESS, StatusCode.ADDSUCCESS);
    }

    /**
     * deleteEmployee: delete employee by employeeId
     *
     * @param employeeId    employee id
     * @return  success: {true, "删除成功", 203}
     */
    @Override
    public ResponseResult deleteEmployee(String employeeId, String accountId) {
        if (StringUtils.isBlank(employeeId)) {
            log.info("参数为空,删除职员失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        int result = employeeMapper.deleteByPrimaryKey(employeeId);
        if (result == 0) {
            log.info("删除职员执行失败");
            return new ResponseResult(false, ResultType.DELETE_ERROR, StatusCode.DELETEERROR);
        }
        log.info("删除了 " + result + " 条职员数据");
        Employee employee = new Employee();
        employee.setEmployeeId(employeeId);
        employee.setEmployeeUpdatorAccountId(accountId);
        employeeMapper.updateByPrimaryKeySelective(employee);
        log.info("Employee Service -> deleteEmployee 删除职员成功");
        return new ResponseResult(result, true, ResultType.DELETE_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    /**
     * deleteEmployeeByPositionId: delete employee by positionId
     *
     * @param employeePositionId    employee position id
     * @return  success: {true, "删除成功", 203}
     */
    @Override
    public ResponseResult deleteEmployeeByPositionId(String employeePositionId) {
        if (StringUtils.isBlank(employeePositionId)) {
            log.info("参数为空,删除职员失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        int result = employeeMapper.deleteByPositionId(employeePositionId);
        if (result == 0) {
            log.info("通过职位ID删除职员执行失败");
            return new ResponseResult(false, ResultType.DELETE_ERROR, StatusCode.DELETEERROR);
        }
        log.info("Employee Service -> deleteEmployeeByPositionId 删除职员成功");
        return new ResponseResult(result, true, ResultType.DELETE_SUCCESS, StatusCode.DELETESUCCESS);
    }

    /**
     * updateEmployee: update employee
     *
     * @param employee  employee
     * @return  success: {true, "更新成功", 204}
     */
    @Override
    public ResponseResult updateEmployee(Employee employee, String accountId) {
        if (employee == null) {
            log.info("参数为空,更新职员信息失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        employee.setEmployeeUpdatorAccountId(accountId);
        if (employeeMapper.updateByPrimaryKeySelective(employee) == 0) {
            log.info("更新职员信息执行失败");
            return new ResponseResult(false, ResultType.UPDATE_ERROR, StatusCode.UPDATEERROR);
        }
        log.info("Employee Service -> updateEmployee 更新职员成功");
        return new ResponseResult(true, ResultType.UPDATE_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    /**
     * queryOne: query one employee by employeeId
     *
     * @param employeeId    employee id
     * @return  success: {employeeInfoVO, true, "查询成功", 201}
     */
    @Override
    public ResponseResult queryOne(String employeeId) {
        if (StringUtils.isBlank(employeeId)) {
            log.info("参数为空,查询职员信息失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        EmployeeInfoVO employeeInfoVO = new EmployeeInfoVO();
        Employee employee = employeeMapper.selectByPrimaryKey(employeeId);
        if (employee == null) {
            log.info("查询职员信息执行失败");
            return new ResponseResult(false, ResultType.FIND_ERROR, StatusCode.FINDERROR);
        } else {
            log.info("职员查询结果: " + employee.toString());
            employeeInfoVO.setEmployeeId(employee.getEmployeeId());
            employeeInfoVO.setEmployeeName(employee.getEmployeeName());
            employeeInfoVO.setEmployeeNickname(employee.getEmployeeNickname());
            employeeInfoVO.setEmployeeGender(employee.getEmployeeGender());
            // 根据部门编号查出部门名称
            employeeInfoVO.setEmployeeDepartmentName(departmentMapper.selectDepartmentNameByPrimaryKey(employee.getEmployeeDepartmentId()));
            log.info("职员部门名称查询结果: " + employeeInfoVO.getEmployeeDepartmentName());
            // 根据职位编号查询职位名称
            employeeInfoVO.setEmployeePositionName(positionMapper.selectPositionNameByPrimaryKey(employee.getEmployeePositionId()));
            log.info("职员职位名称查询结果: " + employeeInfoVO.getEmployeePositionName());
            // 根据角色编号查询角色名称
            String roleName = (String) authorityFeign.queryRoleName(employee.getEmployeeRoleId()).getData();
            if (roleName == null) {
                return new ResponseResult(false, ResultType.FIND_ERROR, StatusCode.FINDERROR);
            }else {
                employeeInfoVO.setEmployeeRoleName(roleName);
            }
            employeeInfoVO.setEmployeeEmail(employee.getEmployeeEmail());
            employeeInfoVO.setEmployeeMobile(employee.getEmployeeMobile());
            employeeInfoVO.setEmployeeTel(employee.getEmployeeTel());
            employeeInfoVO.setEmployeeSeat(employee.getEmployeeSeat());
            // 根据账户编号查询账户名称
            employeeInfoVO.setEmployeeCreatorAccountName(accountMapper.selectAccountNameByPrimaryKey(employee.getEmployeeCreatorAccountId()));
            employeeInfoVO.setEmployeeCreatedTime(employee.getEmployeeCreatedTime());
            // 根据账户编号查询账户名称
            if (employee.getEmployeeUpdatorAccountId() != null) {
                employeeInfoVO.setEmployeeUpdatorAccountName(accountMapper.selectAccountNameByPrimaryKey(employee.getEmployeeUpdatorAccountId()));
            }
            employeeInfoVO.setEmployeeUpdatedTime(employee.getEmployeeUpdatedTime());
            employeeInfoVO.setEmployeeRemarks(employee.getEmployeeRemarks());
            log.info("职员信息VO: " + employeeInfoVO.toString());
        }
        log.info("Employee Service -> queryOne 查询职员成功");
        return new ResponseResult(employeeInfoVO, true, ResultType.FIND_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    /**
     * queryName: get employee nickname by employeeId
     *
     * @param employeeId    employee id
     * @return  success: {employeeName, true, "查询成功", 201}
     */
    @Override
    public ResponseResult queryNickname(String employeeId) {
        if (StringUtils.isBlank(employeeId)) {
            log.info("参数为空,查询职员昵称失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        String employeeNickname = employeeMapper.selectEmployeeNicknameByPrimaryKey(employeeId);
        if (employeeNickname == null) {
            log.info("查询职员昵称执行失败");
            return new ResponseResult(false, ResultType.FIND_ERROR, StatusCode.FINDERROR);
        }
        log.info("Employee Service -> queryNickname 查询职员昵称成功");
        log.info("职员昵称查询结果: " + employeeNickname);
        return new ResponseResult(employeeNickname, true, ResultType.FIND_SUCCESS, StatusCode.FINDSUCCESS);
    }

    /**
     * queryAll: query all employees
     *
     * @return  success: {employeeList, true, "查询成功", 201}
     */
    @Override
    public ResponseResult queryAll() {
        List<Employee> employeeList = employeeMapper.findAllEmployee();
        if (CollectionUtils.isEmpty(employeeList)) {
            log.info("没有查到职员");
            return new ResponseResult(false, ResultType.FIND_NULL, StatusCode.FINDNULL);
        }
        List<EmployeeInfoVO> employeeInfoVOList = new ArrayList<>();
        for (Employee employee : employeeList) {
            EmployeeInfoVO employeeInfoVO = new EmployeeInfoVO();
            employeeInfoVO.setEmployeeId(employee.getEmployeeId());
            employeeInfoVO.setEmployeeName(employee.getEmployeeName());
            employeeInfoVO.setEmployeeNickname(employee.getEmployeeNickname());
            employeeInfoVO.setEmployeeGender(employee.getEmployeeGender());
            // 根据部门编号查出部门名称
            employeeInfoVO.setEmployeeDepartmentName(departmentMapper.selectDepartmentNameByPrimaryKey(employee.getEmployeeDepartmentId()));
            // 根据职位编号查询职位名称
            employeeInfoVO.setEmployeePositionName(positionMapper.selectPositionNameByPrimaryKey(employee.getEmployeePositionId()));
            // 根据角色编号查询角色名称
            String employeeId = employee.getEmployeeRoleId();
            String roleName = (String) authorityFeign.queryRoleName(employeeId).getData();
            if (roleName == null) {
                return new ResponseResult(false, ResultType.FIND_ERROR, StatusCode.FINDERROR);
            }else {
                employeeInfoVO.setEmployeeRoleName(roleName);
            }
            employeeInfoVO.setEmployeeEmail(employee.getEmployeeEmail());
            employeeInfoVO.setEmployeeMobile(employee.getEmployeeMobile());
            employeeInfoVO.setEmployeeTel(employee.getEmployeeTel());
            employeeInfoVO.setEmployeeSeat(employee.getEmployeeSeat());
            // 根据账户编号查询账户名称
            employeeInfoVO.setEmployeeCreatorAccountName(accountMapper.selectAccountNameByPrimaryKey(employee.getEmployeeCreatorAccountId()));
            employeeInfoVO.setEmployeeCreatedTime(employee.getEmployeeCreatedTime());
            // 根据账户编号查询账户名称
            if (employee.getEmployeeUpdatorAccountId() != null) {
                employeeInfoVO.setEmployeeUpdatorAccountName(accountMapper.selectAccountNameByPrimaryKey(employee.getEmployeeUpdatorAccountId()));
            }
            employeeInfoVO.setEmployeeUpdatedTime(employee.getEmployeeUpdatedTime());
            employeeInfoVO.setEmployeeRemarks(employee.getEmployeeRemarks());
            employeeInfoVOList.add(employeeInfoVO);
        }
        log.info("Employee Service -> queryAll 查询所有职员成功");
        return new ResponseResult(employeeInfoVOList, true, ResultType.FIND_SUCCESS, StatusCode.OPERATIONSUCCESS);
    }

    @Override
    public ResponseResult queryAllEmployee() {
        List<Employee> employeeList = employeeMapper.findAllEmployee();
        if (CollectionUtils.isEmpty(employeeList)) {
            log.info("没有查到职员");
            return new ResponseResult(false, ResultType.FIND_NULL, StatusCode.FINDNULL);
        }
        Map<String, String> employeeMap = new HashMap<>();
        for (Employee employee : employeeList) {
            employeeMap.put(employee.getEmployeeNickname(), employee.getEmployeeId());
        }
        log.info("Employee Service -> queryAllEmployee 查询所有职员列表成功");
        return ResponseResult.resultSuccess(employeeMap,"search successful");
    }

    /**
     * checkIsExistByPositionId: check if has employee by positionId
     *
     * @param employeePositionId    employee position id
     * @return  success: {result, true, "查询数据存在", 201}
     */
    @Override
    public ResponseResult checkIsExistByPositionId(String employeePositionId) {
        if (StringUtils.isBlank(employeePositionId)) {
            log.info("参数为空,查询职员失败");
            return new ResponseResult(false, ResultType.PARAMETER_NULL, StatusCode.PARAMETERNULL);
        }
        int result = employeeMapper.checkIsHaveEmployeeByEmployeePositionId(employeePositionId);
        if (result == 0) {
            log.info("没有找到该职位ID对应的职员");
            return new ResponseResult(false, ResultType.FIND_NULL, StatusCode.FINDNULL);
        }
        return new ResponseResult(result, true, ResultType.FIND_EXIST, StatusCode.FINDSUCCESS);
    }

    @Override
    public ResponseResult setDefaultRoleId(String roleId) {
        ResponseResult responseResult=new ResponseResult();
        try{
            int num = employeeMapper.selectByRoleId(roleId);
            if(num>0){
                boolean flag = employeeMapper.updateByRoleId(DataCommon.DEFAULT_ROLE_ID,roleId);
                if(!flag){
                    responseResult=ResponseResult.responseResult(false,false,"update roleRoleId failed!", StatusCode.UPDATEERROR, DataCommon.ICON_ERROR);
                }else{
                    responseResult=ResponseResult.responseResult(true,true,"update roleRoleId success!", StatusCode.UPDATESUCCESS, DataCommon.ICON_SUCCESS);
                }
            }
        }catch (NullPointerException e){
            e.printStackTrace();
            log.info("update roleId failed! NullPointerException!");
            responseResult=ResponseResult.responseResult(false,false,"update roleRoleId failed! Can't find the roleId!", StatusCode.FINDNULL, DataCommon.ICON_ERROR);
        }catch (Exception e){
            e.printStackTrace();
            log.info("update roleId failed! unexpected Exception!");
            responseResult=ResponseResult.responseResult(false,false,"update roleId failed! unexpected Exception !", StatusCode.EXCEPTIONERROR, DataCommon.ICON_ERROR);
        }
        return responseResult;
    }
}